package org.framework.lazy.cloud.network.heartbeat.server.netty.proxy.http.advanced;


import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.http.server.AbstractHandleHttpReportClientProxyClientTransferResponseTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;
import org.springframework.stereotype.Component;
import org.wu.framework.core.utils.ObjectUtils;


/**
 * 服务端处理客户端代理到服务端的请求
 * HTTP_REPORT_CLIENT_PROXY_CLIENT_TRANSFER_CONNECTION_
 */
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Slf4j
@Component
public class ServerHandleHttpReportClientProxyClientTransferResponseTypeAdvanced
        extends AbstractHandleHttpReportClientProxyClientTransferResponseTypeAdvanced<NettyProxyMsg> {


    /**
     * 处理当前数据
     *
     * @param nettyChannelContext 当前通道
     * @param nettyProxyMsg        通道数据
     */
    @Override
    public void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
        Channel channel = nettyChannelContext.channel();
       // 将返回数据下发客户端
        Channel transferNextChannel = ChannelAttributeKeyUtils.getTransferNextChannel(channel);

        if(ObjectUtils.isNotEmpty(transferNextChannel)) {
            log.info("目标客户端返回数据通过服务端下发到原始通道");
            NettyProxyMsg responseProxyMsg = new NettyProxyMsg();
            responseProxyMsg.setData(nettyProxyMsg.getData());
            responseProxyMsg.setType(ProxyMessageType.HTTP_DISTRIBUTE_CLIENT_PROXY_CLIENT_TRANSFER_RESPONSE_);
            transferNextChannel.writeAndFlush(responseProxyMsg);
        }else {
            log.error("无法将数据下发给原始客户端");
        }

    }

}
